import pyautogui as pg
import os
import time
import pyperclip
import requests
import json
import psutil
import sys
import threading

def get_resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)


# 扫描指定目录下的文件，运行名称里有QDJJ或者以斯维尔清单开头的文件
def open_software(dir_path) :
    file_list = os.listdir(dir_path)
    list = []
    for file_name in file_list :
        if (file_name.startswith("斯维尔清单") or "QDJJ" in file_name):
            list.append(file_name)
    os.startfile(dir_path + "\\" + list[0])

 
def reset_softWare_Default():
    time.sleep(20)
    order = pg.locateCenterOnScreen(get_resource_path('pictures/order_no.png'), confidence=0.6)
    if order == None :
        raise Exception ("program not open directly")
    pg.rightClick(order)
    pg.hotkey("up")
    pg.hotkey("enter")
    time.sleep(1)
    pg.hotkey("right")
    pg.hotkey("enter")
    pg.hotkey("left")
    pg.hotkey("enter")
    pg.hotkey("right")
    pg.hotkey("enter")   

def open_file(target_file_path):
    if not os.path.exists(target_file_path) :
        raise Exception ("file download failed")
    time.sleep(15)
    # 检测到提示框 并按下确定键
    tips = pg.locateCenterOnScreen(get_resource_path('pictures/tips.png'), confidence=0.6)
    time.sleep(2)
    if tips is not None:
        pg.click(tips)
        # print("tips is not null")
        pg.hotkey("esc")
        time.sleep(1)

    time.sleep(1)
    pg.click(tips)
    pg.hotkey("esc")
    # 按下打开文件按钮，选择打开文件，复制文件地址
    open_file = pg.locateCenterOnScreen(get_resource_path('pictures/open_file.png'), confidence=0.6)
    if open_file is None:
        raise Exception('can not find open_file button')
    # print(open_file)
    pg.click(open_file)
    pyperclip.copy(target_file_path)
    pg.hotkey('Ctrl','v')
    time.sleep(2)
    pg.hotkey("Enter")
    time.sleep(1)
    pg.hotkey("Enter")
    time.sleep(1)
    pg.hotkey("Enter")

def check_project_number_is_null():
    time.sleep(2)
    # pg.hotkey("tab")
    # pg.hotkey("tab")
    pyperclip.copy("none")
    pg.hotkey("right")
    time.sleep(1)
    pg.hotkey("right")
    # 解锁单元格
    pg.hotkey("shift", "F10")
    pg.hotkey("w")
    pg.hotkey("space")
    pg.hotkey("ctrl", "c")
    number = pyperclip.paste()
    if number != "none" :
        return
    else :
        i = 1
        retry = 0
        while True :
            pyperclip.copy("none")
            pg.hotkey("ctrl", "c")
            pre_number = pyperclip.paste()
            if (pre_number != "none" and pre_number != " " and pre_number != "  ") :
                retry += 1
                i -= 1
                if retry >= 2 :
                    break
            pyperclip.copy(str(i))
            time.sleep(1)
            pg.hotkey("ctrl", "v")
            if i == 1 :
                pyperclip.copy("none")
                # 检测是否输入成功
                time.sleep(1)
                pg.hotkey("ctrl", "a")
                pg.hotkey("ctrl", "c")
                # print(pyperclip.paste())none
                if (pyperclip.paste() != str(i)) :
                    pg.hotkey("enter")
                    pg.hotkey("right")
                    time.sleep(1)
                    # 解锁单元格
                    pg.hotkey("shift", "F10")
                    pg.hotkey("w")
                    pg.hotkey("space")
                    i = 1 
                    continue
            pg.hotkey("enter")
            pg.hotkey("down")
            time.sleep(1)
            # 解锁单元格
            pg.hotkey("shift", "F10")
            pg.hotkey("w")
            pg.hotkey("space")
            time.sleep(2)
            if i > 100:
                raise Exception('too many project numbers need to be filled in')
            i += 1

def fill_project_info():
    time.sleep(2)
    info_is_null = pg.locateCenterOnScreen(get_resource_path('pictures/fill_project_info.png'), confidence=0.6)
    if info_is_null is not None :
        pg.hotkey("right")
        count = 0
        while True :
            pyperclip.copy("1")
            pg.hotkey("ctrl", "v")
            pg.hotkey("enter")
            pg.hotkey("down")
            pg.hotkey("space")
            count += 1
            if (count > 6):
                break
        pg.hotkey("tab")
        pg.hotkey("enter")
    return

def export_file(dir_path):
    time.sleep(2)
    electronic_button = pg.locateCenterOnScreen(get_resource_path('pictures/button.png'), confidence=0.6)
    if electronic_button is None:
        raise Exception('can not find electronic_button button')
    pg.click(electronic_button)
    time.sleep(1)
    checkbox = pg.locateCenterOnScreen(get_resource_path('pictures/checkbox.png'), confidence=0.6)
    if checkbox is None:
        raise Exception('can not find checkbox button')
    pg.click(checkbox)
    time.sleep(1)
    box2 = pg.locateCenterOnScreen(get_resource_path('pictures/box2.png'), confidence=0.6)
    pg.click(box2)
    time.sleep(1)
    export_xml = pg.locateCenterOnScreen(get_resource_path('pictures/export_xml.png'), confidence=0.6)
    if export_xml is None:
        raise Exception('can not find export_xml button')
    pg.click(export_xml)
    pg.hotkey("Down")
    pg.hotkey("Enter")
    fill_project_info()
    # 复制导出后的文件名称
    time.sleep(1)
    pg.hotkey('ctrl','c')
    time.sleep(1)
    xml_file_name = pyperclip.paste()
    pg.hotkey("Enter")
    # 检测导出成功窗口
    i = 0
    while True :
        time.sleep(5)
        i += 1
        success = pg.locateCenterOnScreen(get_resource_path('pictures/export_success.png'), confidence=0.6)
        # if i == 36 and not os.path.isfile(dir_path + xml_file_name) :
        #     raise Exception('error by export xml, didnt find xml file')
        if success == None :
            # print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + ':::正在循环中')
            time.sleep(1)
            if i >= 140 :
                raise Exception('wating export time out')
        else :
            # print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) + ':::导出完成')
            time.sleep(1)
            pg.click(success)
            pg.hotkey("Enter")
            break
    # 返回生成output的xml文件
    return xml_file_name


# 关闭软件
def close_software():
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        process_name = p.name()
        if process_name.startswith('QDJJ'):
            # 杀掉指定进程
            # print('kill process: name: %s - pid: %s' %(process_name, pid))
            find_kill = 'taskkill -f -pid %s' % pid
            os.popen(find_kill)

# 导出成功
def export_success(id, file_name):
    url = '''http://127.0.0.1:9135/rpa/runSuccess'''
    data = {
        "id" : id,
        "file_name" : file_name
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers= headers)
# 异常处理
def export_failed(id, errorMsg):
    url = '''http://127.0.0.1:9135/rpa/runFailed'''
    data = {
        "id" : id,
        "errMsg": errorMsg
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers=headers)


pg.FAILSAFE=False

# 程序被唤起 参数为文件本地地址 文件id
dir_path = sys.argv[1]
need_export_file_name = sys.argv[2]
id = int(sys.argv[3])


try :
    # 桌面软件地址
    software_path = 'D:\\'
    # 打开导出桌面软件
    open_software(software_path)
    # 在桌面软件中打开文件
    open_file(dir_path + need_export_file_name)
    # 恢复软件默认设置
    reset_softWare_Default()
    check_project_number_is_null()
    # 执行点击流程导出软件
    xml_file_name = export_file(dir_path)
    # print(xml_file_name)
    # 导出成功
    export_success(id, xml_file_name)
    # 检测到导出成功窗口后5秒关闭软件
    time.sleep(5)
    close_software()  
except Exception as e:
    export_failed(id, str(e))
    close_software()
